import {Component, OnInit} from '@angular/core';
import {Globals} from '../../../globals';
import {PageHelper} from '../../../utils/page-helper-model';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {BaseService} from '../../../shared/service/base.service';
import {Consts} from '../../../config/consts';
import {ApiUrl} from '../../../config/api-url';

@Component({
  selector: 'app-device-distribution',
  templateUrl: './device-distribution.component.html',
  styleUrls: ['./device-distribution.component.less']
})
export class DeviceDistributionComponent implements OnInit {

  isMobile = Globals.isMobile();
  listOfData: any;
  // 分页
  pageHelper: PageHelper = new PageHelper;
  pageHelper2: PageHelper = new PageHelper;
  formModel: FormGroup;
  expandSet = new Set<number>();
  // 步骤几
  current = 0;
  agencyList: any;
  isSpinning: boolean;
  // 不分配设备
  notDistributionDeviceList = [];
  distributionCount = 0;
  // 机构名称
  agencyName: string;

  // 设备绑定结果
  deviceList: any;
  distributionVerdict = false;

  userInfo: any;


  // 指定返佣按钮
  isVisible: boolean;

  constructor(private fb: FormBuilder, public baseService: BaseService) {
  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.buildForm();
    this.getAllAgencyOfName();
  }

  buildForm() {
    this.formModel = this.fb.group({
      startDevice: ['', [Validators.required]],
      endDevice: ['', [Validators.required]],
      agencyId: ['', [Validators.required]],
      rebateAgencyId: [''],
      isAnew: [0, [Validators.required]],
      syntheticType: ['', []],
    })
    ;
  }

  /**
   * 上、下页
   * @param $event
   */
  nzPageIndexChange($event: number) {

    this.pageHelper.currentPage = $event;
    var promise = new Promise((resolve) => {
      this.baseService.findListByMuchCondition(ApiUrl.DeviceUrl + '/findDistributionDevice', this.formModel.value, this.pageHelper).subscribe(
        data => {
          if (data.status == 0) {
            console.log("请求成功")
            this.listOfData = data.data.list;
            this.pageHelper.totalItems = data.data.total;
            this.pageHelper.numPages = data.data.pages;
            this.checkedAll(true);
          } else {
            this.baseService.layer.messageError(data.msg);
          }
          resolve();
        }
      );
    });

    promise.then((res:any) => {
      console.info("11111");
      for (let item of this.notDistributionDeviceList) {
        console.table(item);
        this.baseService.zorro.onItemChecked(item.id, false);
      }
    });
  }

  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  // 选中全部
  checkedAll($event: boolean) {
    // 在这里获取当页的所有id

    // 先将集合清空
    this.baseService.zorro.listOfCurrentPageData = this.listOfData;

    // 调用全选方法
    this.baseService.zorro.onAllChecked($event);
  }

  // 选中单个
  checkedItem(deviceId: any, $event: boolean, type: number) {
    if (!$event) {
      // 收集不分配的设备
      this.notDistributionDeviceList.push({id: deviceId});
      this.distributionCount = this.distributionCount - 1;
    } else {
      this.distributionCount = this.distributionCount + 1;
    }
    this.baseService.zorro.onItemChecked(deviceId, $event);
  }

  // 重新分配
  anewAllocate(){
    this.pageHelper.numPages = 0;
    this.pageHelper.currentPage = 1;
    this.formModel.get("isAnew").setValue(1);
    this.submitForm(1);
  }

  // 新分配
  noAnewAllocate(){
    this.pageHelper.numPages = 0;
    this.pageHelper.currentPage = 1;
    this.formModel.get("isAnew").setValue(0);
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isSpinning = false;
      return;
    }

    this.submitForm(1);
  }


  submitForm(number) {
    this.isSpinning = true;
    // 校验非空和其他非法输入
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isSpinning = false;
      return;
    }
    for (let i = 0; i < this.agencyList.length; i++) {
      if (this.agencyList[i].id == this.formModel.get('agencyId').value) {
        this.agencyName = this.agencyList[i].name;
        break;
      }
    }

    // tslint:disable-next-line:max-line-length
    this.baseService.findListByMuchCondition(ApiUrl.DeviceUrl + '/findDistributionDevice', this.formModel.value, this.pageHelper).subscribe(
      data => {
        if (data.status == 0) {
          // console.log("请求成功")
          this.listOfData = data.data.list;
          this.pageHelper.totalItems = data.data.total;
          this.pageHelper.numPages = data.data.pages;
          this.isSpinning = false;
          if (this.distributionCount == 0) {
            this.distributionCount = data.data.total;
          }
          if (number == 1) {
            this.current++;
          }
          this.checkedAll(true);
        } else {
          this.baseService.layer.messageError(data.msg);
          this.isSpinning = false;
        }
      }
    );
  }

  nextStep(number) {
    this.isSpinning = true;
    let body = {
      startDevice: this.formModel.get('startDevice').value,
      endDevice: this.formModel.get('endDevice').value,
      agencyId: this.formModel.get('agencyId').value,
      isAnew: this.formModel.get('isAnew').value,
      // rebateAgencyId: this.formModel.get('rebateAgencyId').value,
      notDistributionDeviceList: this.notDistributionDeviceList,
      syntheticType: this.formModel.get('syntheticType').value,
    };
    this.baseService.put(ApiUrl.DeviceUrl + '/distributionDevice', body).subscribe(res => {
      if (res.status == 0) {
        console.log(res);
        this.deviceList = res.data;
        this.pageHelper2.totalItems = res.data.distributionFailCount;
        this.pageHelper2.numPages = 1;
        this.isSpinning = false;
        if (number == 1) {
          this.current++;
        }
      } else {
        this.baseService.layer.messageError(res.msg);
        this.isSpinning = false;
      }
    });
  }

  // 上一步
  lastStep(number: number) {
    // 清空不选的设备
    this.notDistributionDeviceList.length = 0;

    this.current--;
    this.distributionCount = 0;
    this.pageHelper.totalItems = 0;
    this.pageHelper.numPages = 0;
  }

  onCurrentPageDataChange($event: ReadonlyArray<any>) {
    console.log($event);
  }

  updateRebateAgencyId($event: any) {
    this.formModel.get('rebateAgencyId').setValue($event);
  }

  handleCancel() {
    this.isVisible =false;
  }

  handleOk() {
    this.submitForm(1);
    this.isVisible = false;
  }
}
